import React, { Component } from 'react'
import { Button, Form, Table, Modal, message } from 'antd'
import moment from 'moment'
import { cloneDeep } from 'lodash'

import RoleModal from './components/RoleModal'
import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import { list2Tree } from '@/pages/Dashboard/components/Inner/utils/treeUtils'
import { checkPermission } from '@/components/AuthComponent/utils'

import './index.less'

const { resource, role: roleApi, permission } = address

export default class Role extends Component {
  columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
    },
    {
      title: '角色简介',
      dataIndex: 'desc',
    },
    {
      title: '对应账户数量',
      dataIndex: 'userCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '操作',
      dataIndex: 'local_remote',
      render: (v, record) => {
        return record.type !== 'DEFAULT' && <div className="action">
          {
            checkPermission('user-role-detail') &&
          <span className="common-operation" onClick={() => this.updateRole(record, 'check')}>查看</span>
          }
          {
            checkPermission('user-role-update') &&
            <span className="common-operation" onClick={() => this.updateRole(record, 'update')}>修改</span>
          }
          {
            checkPermission('user-role-delete') &&
          <span className="common-operation" onClick={() => this.delete(record)}>删除</span>
          }
        </div>
      },
    },
  ];

  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      checkData: {},
      total: 0,
      list: [],
      btnLoading: false,
    }
    this.handleRecord = {}
    this.flag = 'create'
    this.searchOption = {
      pageNum: 1,
      pageSize: 100,
    }
  }

  componentDidMount() {
    this.getList()
    this.getResourceList()
  }

  getList = async(values = {}) => {
    this.setState({
      loading: true,
    })
    this.searchOption = {
      ...this.searchOption,
      ...values,
    }
    const { status, data = {}} = await request().get(roleApi.getList, {
      params: {
        ...this.searchOption,
      },
    })
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.setState({
        total: data.total || 0,
        list: data.data || [],
      })
    }
  }

  search = (values) => {
    this.searchOption.pageNum = 1
    this.getList()
  }

  onPageChange = (current, pageSize) => {
    const { searchOption } = this
    searchOption.pageNum = current
    searchOption.pageSize = pageSize
    this.getList()
  };

  addRole = () => {
    this.flag = 'create'
    this.handleRecord = {
      treeData: list2Tree(cloneDeep(this.resourceList)),
    }
    this.setState({
      visible: true,
    })
  }

  /**
   *
   * @param {修改角色} record
   */
  updateRole = async(record, flag) => {
    this.flag = flag
    // 获取角色权限列表
    const { status, data = {}} = await request().get(permission.create, {
      params: {
        roleId: record.id,
      },
    })
    if (status === 200) {
      const permissions = (data.data || []).map(v => v.resource_id) // 角色所拥有的资源id
      const resourceList = this.resourceList.map(v => {
        return {
          ...v,
          checked: permissions.includes(v.id),
        }
      })
      this.handleRecord = {
        ...record,
        treeData: list2Tree(resourceList),
      }
      this.setState({
        visible: true,
      })
    }
  }

  /**
   * 删除角色
   */
  delete = async(record) => {
    const { status, data = 0 } = await request().get(roleApi.getRoleBindCount.format({ id: record.id }))
    if (status === 200 && data > 0) {
      return message.warn('该角色已关联账户，无法删除')
    }
    this.handleRecord = record
    Modal.confirm({
      content: `是否要删除${record.name}角色？`,
      onOk: async() => {
        const { status } = await request().delete(roleApi.getRoleDetail.format({ id: record.id }))
        if (status === 200) {
          Modal.info({
            title: '已提交申请，请等待管理员审核',
            okText: '我知道了',
            onOk: () => {},
          })
          this.getList()
        }
      },
    })
  }

  /**
   * 获取所有权限
   */
  getResourceList = async() => {
    const { status, data = {}} = await request().get(resource.getList)
    if (status === 200) {
      this.resourceList = (data.data || []).map(v => {
        return {
          id: v.id,
          name: v.name,
          checked: false,
          parentId: v.parent_id,
        }
      })
    }
  }

  onOk = async(values) => {
    if (this.flag === 'check') {
      return this.setState({
        visible: false,
      })
    }
    this.flag === 'create' ? this.onCreate(values) : this.onUpdate(values)
  }

  onCreate = async({ name, desc, treeList }) => {
    const resourceIds = treeList.filter(v => v.checked).map(v => v.id)
    const { status } = await request().post(roleApi.createRole, {
      name,
      desc,
      resourceList: resourceIds,
    })
    if (status >= 200 && status < 400) {
      Modal.info({
        title: '已提交申请，请等待管理员审核',
        okText: '我知道了',
        onOk: () => {},
      })
      this.setState({
        visible: false,
      })
      this.getList()
    }
  }

  onUpdate = async({ name, desc, treeList }) => {
    const resourceIds = treeList.filter(v => v.checked).map(v => v.id)
    const { status } = await request().put(roleApi.getRoleDetail.format({ id: this.handleRecord.id }), {
      name,
      desc,
      resourceList: resourceIds,
    })
    if (status === 200) {
      Modal.info({
        title: '已提交申请，请等待管理员审核',
        okText: '我知道了',
        onOk: () => {},
      })
      this.setState({
        visible: false,
      })
      this.getList()
    }
  }

  render() {
    const { visible, loading, list } = this.state
    return <div className="Role">
      <Form layout="inline">
        {
          checkPermission('user-role-add') &&
          <Form.Item style={{ marginLeft: 'auto' }}>
            <Button type="primary" onClick={this.addRole}>添加角色</Button>
          </Form.Item>
        }

      </Form>
      <Table
        loading={loading}
        className="mt24"
        columns={this.columns}
        dataSource={list}
        rowKey="id"
      />
      {
        visible &&
        <RoleModal
          treeData={this.handleRecord.treeData || []}
          visible={visible}
          onCancel={() => this.setState({ visible: false })}
          handleRecord={this.handleRecord}
          flag={this.flag}
          onOk={this.onOk}
        />
      }
    </div>
  }
}
